package com.qianyucc.blog.controller.admin;

import cn.hutool.core.util.*;
import com.qianyucc.blog.model.dto.*;
import com.qianyucc.blog.model.entity.*;
import com.qianyucc.blog.model.vo.*;
import com.qianyucc.blog.mapper.*;
import com.qianyucc.blog.utils.*;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.*;

import static com.qianyucc.blog.global.Constants.*;

/**
 * @author lijing
 * @e-mail 1413979079@qq.com
 * @date 2020-02-06 17:13
 * @description 草稿
 */
@RestController
@RequestMapping("admin/draft")
public class DraftController {
    @Autowired
    private DraftMapper draftMapper;

    @ApiOperation("获取所有草稿")
    @GetMapping("/")
    public List<DraftVO> getAllDrafts() {
        List<DraftVO> draftVOS = draftMapper.findAll()
                .stream()
                .map(DraftVO::create)
                .collect(Collectors.toList());
        return draftVOS;
    }

    @ApiOperation("根据id获取对应草稿信息")
    @GetMapping("/{id}")
    public DraftDO getById(@PathVariable String id) {
        DraftDO draftDO = draftMapper.findById(id);
        return draftDO;
    }

    @ApiOperation("新增草稿")
    @PostMapping("/")
    public Map<String, Object> saveDraft(@RequestBody DraftDTO draftDTO) {
        // 生成唯一id
        String id = IdUtil.simpleUUID();
        DraftDO draftDO = new DraftDO();
        draftDO.setTitle(draftDTO.getTitle());
        draftDO.setContent(draftDTO.getContent());
        draftDO.setGmtUpdate(System.currentTimeMillis());
        draftDO.setGmtCreate(draftDO.getGmtUpdate());
        draftDO.setId(id);

        draftMapper.insDraft(draftDO);
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "文章已自动保存，上次保存时间：" + Utils.formatDate(draftDO.getGmtUpdate(), DATE_TIME_PATTERN));
        map.put("id", id);
        return map;
    }

    @ApiOperation("更新草稿")
    @PutMapping("/")
    public Map<String, Object> updDraft(@RequestBody DraftDTO draftDTO) {
        DraftDO draftDO = new DraftDO();
        String id = draftDTO.getId();
        draftDO.setId(id);
        draftDO.setTitle(draftDTO.getTitle());
        draftDO.setContent(draftDTO.getContent());
        draftDO.setGmtUpdate(System.currentTimeMillis());
        draftMapper.updDraft(draftDO);
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "文章已自动保存，上次保存时间：" + Utils.formatDate(draftDO.getGmtUpdate(), DATE_TIME_PATTERN));
        map.put("id", id);
        return map;
    }

    @ApiOperation("根据id删除指定草稿")
    @DeleteMapping("/{id}")
    public ResultVO get(@PathVariable String id) {
        draftMapper.deleteById(id);
        return ResultVO.ok("删除成功");
    }
}
